package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.behavior.mapper.UnLikesBehaviorMapper;
import com.usian.behavior.service.BehaviorEntryService;
import com.usian.behavior.service.UnLikesBehaviorService;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.behavior.dtos.UnLikesBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApUnlikesBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.utils.threadlocal.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UnLikesBehaviorServiceImpl extends BaseServiceImpl<UnLikesBehaviorMapper, ApUnlikesBehavior> implements UnLikesBehaviorService {
    @Autowired
    private BehaviorEntryService service;

    @Override
    public ResponseResult like(UnLikesBehaviorDto dto) {
        if (dto == null || dto.getArticleId() == null || dto.getType() == null || (dto.getType() != 0 && dto.getType() != 1))
            return paramError;
        Integer userId = ThreadLocalUtils.getUser();
        if (userId == null) return needLogin;
        ApBehaviorEntry entry = service.findByUserIdOrEquipmentId(userId);
        ApUnlikesBehavior unlikesBehavior = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery().eq(ApUnlikesBehavior::getArticleId, dto.getArticleId()).eq(ApUnlikesBehavior::getEntryId, entry.getId()));
        if (unlikesBehavior == null) {
            if (dto.getType() == 0) {
                ApUnlikesBehavior behavior = new ApUnlikesBehavior();
                behavior.setArticleId(dto.getArticleId());
                behavior.setCreatedTime(new Date());
                behavior.setEntryId(entry.getId());
                behavior.setType(0);
                save(behavior);
            } else System.out.println("该不喜欢行为数据不存在");
        } else {
            unlikesBehavior.setType(dto.getType().intValue());
            updateById(unlikesBehavior);
        }

        return okResult;
    }

    @Override
    public ApUnlikesBehavior getUnLikesBehavior(Long articleId, Integer entryId) {
        if (articleId == null || entryId == null) return null;
        return getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery().eq(ApUnlikesBehavior::getArticleId, articleId).eq(ApUnlikesBehavior::getEntryId, entryId));
    }
}
